package ltd.ueic.allypay.alipay.controller;

import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.domain.AlipayTradePagePayModel;
import com.alipay.api.domain.AlipayTradeWapPayModel;
import com.alipay.api.request.AlipayTradeRefundRequest;
import com.alipay.api.response.*;
import ltd.ueic.allypay.alipay.config.AlipayConfig;
import ltd.ueic.allypay.alipay.service.AliPayService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.Map;

/**
 * @author Kevin Yang
 * @version 1.0.0
 * Created by Kevin Yang on 2018/11/30 10:50.
 */
@Controller
@RequestMapping(value = "/test/alipay")
public class AliPayTestController {

    @Autowired
    private AliPayService aliPayService;
    @Autowired
    private AlipayConfig alipayConfig;

    public static void main(String[] args) {
        AlipayClient alipayClient = new DefaultAlipayClient("https://openapi.alipaydev.com/gateway.do",
                "2016092300580616",
                "MIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQC7oUC/olEL06NNhccHtiefZvbIobFXQZyWXsXWdkfPywxqkyUH0O15sqGltHtSV12I8LRfrjh/Orav+zcM5l+cBgrUqRs0tc1EOdinNDCKNbXYP4oFeUHsg3gDgBOgZvydtrx+gF53iahJ4sDfoke4fIzZDUwpBsTUllvau9GEvxw657JVnavjrvbCYzzT9e//2lulXe/mtue5NnQcGquB2tTvrlwV+Ry1LiFqhbVz3cltYdXy/jqbx0iB7iIcNYwfWu1TDhm4GKkSLpulT/fqhb4Ld9fxiF8SNydnSy9cJJvctcEbsrVaZ3Wd7h/4UUtoUts8gnw/O4cUa8ZnhVGNAgMBAAECggEBAIloZ12wRoBNxqtQTFj2aoAPTK3T1Gcdcsqgr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ezWtIJfbB0MLG2KyTT6UR8zLdFliESXKwRCY/AWLGS+a2q4WyfU+nVJwuVcthbymR0eJc7tS1whZd2jXdBrB/M0BsAe91fyqbw0noihLABpskg7JPUlQTeYgHL",
                "json",
                "UTF-8",
                "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAwXt6c2sWEK3yALWnUROYLWRxm3RunzN+ALmIMRYAFVi3dH/GbrlNRCXyPgoOP5JOL8GV3nn5d2Q0SodbuwK3UgA3C6iWXNd3RlU/b/KkemjJBpASlxekPOEdamJO6bb7qXLvb/QhYdOz79L7bygA9sdwzP9TyBUNSAAPIPMvEPY0aOrQF+hOD722JJLncMCKzL5VdRum2UcZGoCtcCKnGRD3mQcIX8ODj/yrKunnIxf/yf9VTjIPShhT6hnayWjyueT5vMa6+Ao1b+960aarV1S0zIRtGr7wufDTz6PyxDaavRaQoDhq48xkfreGCik5gno4u4ZcH6kvev2+XeHFpQIDAQAB",
                "RSA2"); //获得初始化的AlipayClient
        AlipayTradeRefundRequest request = new AlipayTradeRefundRequest();//创建API对应的request类
        request.setBizContent("{" +
                " \"out_trade_no\":\"2018124154227646\"," +
                " \"trade_no\":\"2018120422001498660500588242\"," +
                " \"out_request_no\":\"\"," +
                " \"refund_amount\":\"0.01\"" +
                " }");//设置业务参数
        AlipayTradeRefundResponse response = null;//通过alipayClient调用API，获得对应的response类
        try {
            response = alipayClient.execute(request);
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }
        System.out.print(response.getBody());
    }

    @RequestMapping(value = "/wappay/index")
    public String wappayIndex() {
        return "wappay/index";
    }

    @RequestMapping(value = "/pagepay/index")
    public String pagepayIndex() {
        return "pagepay/index";
    }

    @RequestMapping(value = "/wappay", method = RequestMethod.GET)
    public String payPage() {
        return "wappay/pay";
    }

    @RequestMapping(value = "/close", method = RequestMethod.GET)
    public String closePage() {
        return "wappay/close";
    }

    @RequestMapping(value = "/query", method = RequestMethod.GET)
    public String queryPage() {
        return "wappay/query";
    }

    @RequestMapping(value = "/refund", method = RequestMethod.GET)
    public String refundPage() {
        return "wappay/refund";
    }

    @RequestMapping(value = "/refundquery", method = RequestMethod.GET)
    public String refundqueryPage() {
        return "wappay/refundquery";
    }

    @RequestMapping(value = "/downloadurl", method = RequestMethod.GET)
    public String downloadurlPage() {
        return "wappay/downloadurl";
    }

    @RequestMapping(value = "/trade/wap/pay", method = RequestMethod.POST)
    public void wappay(AlipayTradeWapPayModel bizModel, HttpServletResponse response) {
        AlipayTradeWapPayResponse payResponse = aliPayService.wapPay(bizModel, null, null);
        try {
            // 调用SDK生成表单
            String form = payResponse.getBody();
            response.setContentType("text/html;charset=" + alipayConfig.getCharset());
            //直接将完整的表单html输出到页面
            response.getWriter().write(form);
            response.getWriter().flush();
            response.getWriter().close();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    @RequestMapping(value = "/trade/page/pay", method = RequestMethod.POST)
    public void pagepay(AlipayTradePagePayModel bizModel, HttpServletResponse response) {
        AlipayTradePagePayResponse payResponse = aliPayService.pagePay(bizModel, null, null);
        try {
            // 调用SDK生成表单
            String form = payResponse.getBody();
            response.setContentType("text/html;charset=" + alipayConfig.getCharset());
            //直接将完整的表单html输出到页面
            response.getWriter().write(form);
            response.getWriter().flush();
            response.getWriter().close();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    @RequestMapping(value = "/trade/pay/return", method = RequestMethod.GET)
    public String pay_return(HttpServletRequest request, ModelMap model) {
        try {
            //获取支付宝POST过来反馈信息
            Map<String, String> params = params = aliPayService.getPayReturnParams(request.getParameterMap());
            Boolean verify_result = aliPayService.verifyReturn(params);

            if (verify_result) {//验证成功
                //获取支付宝的通知返回参数，可参考技术文档中页面跳转同步通知参数列表(以下仅供参考)//
                //商户订单号
                String out_trade_no = new String(params.get("out_trade_no").getBytes("ISO-8859-1"), "UTF-8");

                //支付宝交易号
                String trade_no = new String(params.get("trade_no").getBytes("ISO-8859-1"), "UTF-8");
                //////////////////////////////////////////////////////////////////////////////////////////
                //请在这里加上商户的业务逻辑程序代码
                //该页面可做页面美工编辑
                model.put("msg", "验证成功");
                //——请根据您的业务逻辑来编写程序（以上代码仅作参考）——

                //////////////////////////////////////////////////////////////////////////////////////////
            } else {
                //该页面可做页面美工编辑
                model.put("msg", "验证失败");
            }
        } catch (UnsupportedEncodingException e) {
            model.put("msg", "验证失败");
            e.printStackTrace();
        }
        return "wappay/return_url";
    }

    @RequestMapping(value = "/trade/pay/notify", method = RequestMethod.POST)
    public String pay_notify(HttpServletRequest request, ModelMap model) {
        try {
            //获取支付宝POST过来反馈信息
            Map<String, String> params = params = aliPayService.getPayReturnParams(request.getParameterMap());
            Boolean verify_result = aliPayService.verifyReturn(params);

            //获取支付宝的通知返回参数，可参考技术文档中页面跳转同步通知参数列表(以下仅供参考)//
            //商户订单号
            String out_trade_no = new String(request.getParameter("out_trade_no").getBytes("ISO-8859-1"), "UTF-8");
            //支付宝交易号
            String trade_no = new String(request.getParameter("trade_no").getBytes("ISO-8859-1"), "UTF-8");
            //交易状态
            String trade_status = new String(request.getParameter("trade_status").getBytes("ISO-8859-1"), "UTF-8");

            if (verify_result) {//验证成功
                //////////////////////////////////////////////////////////////////////////////////////////
                //请在这里加上商户的业务逻辑程序代码

                //——请根据您的业务逻辑来编写程序（以下代码仅作参考）——

                if (trade_status.equals("TRADE_FINISHED")) {
                    //判断该笔订单是否在商户网站中已经做过处理
                    //如果没有做过处理，根据订单号（out_trade_no）在商户网站的订单系统中查到该笔订单的详细，并执行商户的业务程序
                    //请务必判断请求时的total_fee、seller_id与通知时获取的total_fee、seller_id为一致的
                    //如果有做过处理，不执行商户的业务程序

                    //注意：
                    //如果签约的是可退款协议，退款日期超过可退款期限后（如三个月可退款），支付宝系统发送该交易状态通知
                    //如果没有签约可退款协议，那么付款完成后，支付宝系统发送该交易状态通知。
                } else if (trade_status.equals("TRADE_SUCCESS")) {
                    //判断该笔订单是否在商户网站中已经做过处理
                    //如果没有做过处理，根据订单号（out_trade_no）在商户网站的订单系统中查到该笔订单的详细，并执行商户的业务程序
                    //请务必判断请求时的total_fee、seller_id与通知时获取的total_fee、seller_id为一致的
                    //如果有做过处理，不执行商户的业务程序

                    //注意：
                    //如果签约的是可退款协议，那么付款完成后，支付宝系统发送该交易状态通知。
                }

                //——请根据您的业务逻辑来编写程序（以上代码仅作参考）——
                model.put("msg", "success");    //请不要修改或删除

                //////////////////////////////////////////////////////////////////////////////////////////
            } else {//验证失败
                model.put("msg", "fail");
            }
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return "wappay/notify_url";
    }

    @RequestMapping(value = "/trade/close", method = RequestMethod.POST)
    public String trade_close(String outTradeNo, String tradeNo) {
        AlipayTradeCloseResponse closeResponse = aliPayService.close(outTradeNo, tradeNo, null);
        return closeResponse.getBody();
    }

    @RequestMapping(value = "/trade/query", method = RequestMethod.POST)
    public String trade_query(String outTradeNo, String tradeNo) {
        AlipayTradeQueryResponse queryResponse = aliPayService.query(outTradeNo, tradeNo, null);
        return queryResponse.getBody();
    }

    @RequestMapping(value = "/trade/refund", method = RequestMethod.POST)
    public String trade_refund(String outTradeNo, String tradeNo, String refundAmount, String refundReason, String outRequestNo) {
        AlipayTradeRefundResponse refundResponse = aliPayService.refund(outTradeNo, tradeNo, refundAmount, refundReason, outRequestNo);
        return refundResponse.getBody();
    }

    @RequestMapping(value = "/trade/fastpay/refund/query", method = RequestMethod.POST)
    public String trade_query_refund(String outTradeNo, String tradeNo, String outRequestNo) {
        AlipayTradeFastpayRefundQueryResponse refundQueryResponse = aliPayService.refundQuery(outTradeNo, tradeNo, outRequestNo);
        return refundQueryResponse.getBody();
    }

    @RequestMapping(value = "/data/dataservice/bill/downloadurl/query", method = RequestMethod.POST)
    public String query_bill_downloadurl(String billType, String billDate) {
        AlipayDataDataserviceBillDownloadurlQueryResponse downloadurlQueryResponse = aliPayService.downloadUrl(billType, billDate);
        return downloadurlQueryResponse.getBody();
    }

}
